<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Car as CarModel;
use app\common\model\MerchantCar as MerchantCarModel;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 商家取还车区域管理
 *
 * @icon fa fa-circle-o
 */
class MerchantArea extends Backend
{
    
    /**
     * MerchantArea模型对象
     * @var \app\admin\model\MerchantArea
     */
    protected $model = null;
    protected $merchant_id = null;
    //关联查询
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\MerchantArea;

        $this->view->assign('statuslist',$this->model->getStatusList());
        $this->assignconfig('statuslist',$this->model->getStatusList());

        $merchant_id = $this->request->param('merchant_id', 0);
        $this->merchant_id = $merchant_id;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $builder = $this->model
                ->withJoin(['merchant'])
                ->where($where)
                ->where('merchant_area.is_delete', 1);
            if($this->merchant_id){
                $builder->where('merchant_area.merchant_id', $this->merchant_id);
            }
            $total = $builder
                ->order($sort, $order)
                ->count();

            $list = $builder
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }
        $params = $this->request->param();

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    unset($params['address']);
                    $params['merchant_id'] = $this->merchant_id;
                    $params['createtime'] = time();

                    $result = $this->model->save($params);

                    //添加操作历史
                    if($result){
                        $merchant_area_id = $this->model->id;
                        $log = [
                            'admin_id' => $this->admin['id'],
                            'merchant_id' => $this->merchant_id,
                            'merchant_area_id' => $merchant_area_id,
                            'type' => 1,
                            'operation_filed' => '',
                            'createtime' => time()
                        ];
                        \app\admin\model\MerchantAreaLog::insert($log);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $merchant = \app\common\model\Merchant::where('id', $this->merchant_id)->find();
        $site_area = $this->model->where(['merchant_id' => $this->merchant_id, 'is_delete' => 1])->column('area');
        $siteArea = [];
        if($site_area){
            foreach ($site_area as $key=>$val){
                $siteAreas = [];
                if($val){
                    $newVal = explode(';',$val);
                    foreach ($newVal as $keys=>$vals){
                        $newvals = explode(',',$vals);
                        $siteAreas[] = [
                            $newvals[0],
                            $newvals[1]
                        ];
                    }
                    $siteArea[] = $siteAreas;
                }
            }
        }
//        dump($siteArea);
//        dump(json_encode($siteArea));die;
        $this->view->assign('siteArea', json_encode($siteArea));
        $this->view->assign('merchant', $merchant);
        $this->view->assign('lng', $merchant->longitude);
        $this->view->assign('lat', $merchant->latitude);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? $name : $this->modelValidate;
                        $pk       = $row->getPk();
                        if (!isset($params[$pk])) {
                            $params[$pk] = $row->$pk;
                        }
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    $operation_filed = [];
                    if($params['price'] != $row['price']){
                        $operation_filed[] = '送车价格';
                    }
                    if($params['stay_time'] != $row['stay_time']){
                        $operation_filed[] = '准备时间';
                    }
                    if($params['area'] != $row['area']){
                        $operation_filed[] = '区域位置';
                    }
                    unset($params['address']);
                    $params['updatetime'] = time();
                    $result = $row->save($params);

                    //添加操作历史
                    if($result){
                        $log = [
                            'admin_id' => $this->admin['id'],
                            'merchant_id' => $this->merchant_id,
                            'merchant_area_id' => $ids,
                            'type' => 2,
                            'operation_filed' => $operation_filed ? implode(',', $operation_filed) : '',
                            'createtime' => time()
                        ];
                        \app\admin\model\MerchantAreaLog::insert($log);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $newArea = [];
        if($row['area']){
            $area = explode(';',$row['area']);
            foreach ($area as $key=>$val){
                if($val){
                    $newVal = explode(',',$val);
                    $newArea[$key] = [
                        $newVal[0],
                        $newVal[1]
                    ];
                }
            }
        }

        $merchant = \app\common\model\Merchant::where('id', $this->merchant_id)->find();
        $site_area = $this->model->where(['merchant_id' => $this->merchant_id, 'is_delete' => 1])->column('area');
        $siteArea = [];
        if($site_area){
            foreach ($site_area as $key=>$val){
                $siteAreas = [];
                if($val){
                    $newVal = explode(';',$val);
                    foreach ($newVal as $keys=>$vals){
                        $newvals = explode(',',$vals);
                        $siteAreas[] = [
                            $newvals[0],
                            $newvals[1]
                        ];
                    }
                    $siteArea[] = $siteAreas;
                }
            }
        }
        $this->view->assign('area', json_encode($newArea));
        $this->view->assign('siteArea', json_encode($siteArea));
        $this->view->assign('merchant', $merchant);
        $this->view->assign('lng', $merchant->longitude);
        $this->view->assign('lat', $merchant->latitude);

        $this->view->assign('row', $row);

        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->model->where('id', 'in', $ids)->update(['is_delete' => 2, 'deletetime' => time()]);
        //添加操作历史
        $log = [
            'admin_id' => $this->admin['id'],
            'merchant_id' => $this->merchant_id,
            'merchant_area_id' => $ids,
            'type' => 3,
            'createtime' => time()
        ];
        \app\admin\model\MerchantAreaLog::insert($log);
        $this->success();
    }

}
